<template>
	<div class="zm-readmore">
		<div
			ref="content"
			class="zm-readmore__content"
			:style="{
				height: isLongContent && !showMore ? showHeight + 'px' : 'auto',
				textIndent: textIndent
			}"
		>
			<slot />
		</div>
		<div
			class="zm-readmore__showmore"
			v-if="isLongContent"
			:style="innerShadowStyle"
			@click="toggleReadMore"
		>
			<span
				:style="{
					fontSize,
					color: color
				}"
			>
				{{ showMore ? openText : closeText }}
			</span>
			<i
				class="arrow"
				:class="{
					'el-icon-arrow-down': !showMore,
					'el-icon-arrow-up': showMore
				}"
				:style="{
					fontSize,
					color
				}"
			/>
		</div>
	</div>
</template>
<script>
export default {
	name: "zm-read-more",
	props: {
		// 默认的显示占位高度，单位为px
		showHeight: {
			type: [Number, String],
			default: 200
		},
		// 展开后是否显示"收起"按钮
		toggle: {
			type: Boolean,
			default: true
		},
		// 关闭时的提示文字
		closeText: {
			type: String,
			default: "展开阅读全文"
		},
		// 展开时的提示文字
		openText: {
			type: String,
			default: "收起"
		},
		// 提示的文字颜色
		color: {
			type: String,
			default: "#9044EB"
		},
		// 提示文字的大小
		fontSize: {
			type: String,
			default: "14px"
		},
		// 段落首行缩进的字符个数
		textIndent: {
			type: String,
			default: "1em"
		},
		// open和close事件时，将此参数返回在回调参数中
		index: {
			type: [Number, String],
			default: ""
		}
	},
	computed: {
		paramsChange() {
			return `${this.toggle}-${this.showHeight}`;
		},
		// 展开后无需阴影，收起时才需要阴影样式
		innerShadowStyle() {
			if (this.showMore) return {};
			const { showHeight } = this;
			return {
				backgroundImage: "linear-gradient(-180deg, rgba(255,255,255,0) 0%, #fff 90%)",
				paddingTop: showHeight + "px",
				marginTop: -showHeight + "px"
			};
		}
	},
	data() {
		return {
			isLongContent: false, // 是否需要隐藏一部分内容
			showMore: false // 当前隐藏与显示的状态，true-显示，false-收起
		};
	},
	mounted() {
		this.init();
	},
	methods: {
		init() {
			this.$nextTick(() => {
				const { clientHeight } = this.$refs.content;
				if (clientHeight > this.showHeight) {
					this.isLongContent = true;
					this.showMore = false;
				}
			});
		},
		// 展开或者收起
		toggleReadMore() {
			this.showMore = !this.showMore;
			// 如果toggle为false，隐藏"收起"部分的内容
			if (this.toggle == false) this.isLongContent = false;
			// 发出打开或者收齐的事件
			this.$emit(this.showMore ? "open" : "close", this.index);
		}
	}
};
</script>
<style lang="scss" scoped>
.zm-readmore {
	text-align: left;
	overflow: hidden;
	line-height: 1.8;
	&__showmore {
		position: relative;
		padding-top: 0;
		margin-top: 4px;
		background: none;
		text-align: center;
		@include flex;
		justify-content: center;
		align-items: center;
		.arrow {
			margin-left: 4px;
		}
	}
}
</style>
